<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\HelpAnswer;
use App\Models\HelpRequest;
use Illuminate\Http\Request;

class HelpAnswerController extends Controller
{
    /**
     * 创建新的回答
     */
    public function store(Request $request, HelpRequest $helpRequest)
    {
        $request->validate([
            'content' => 'required|string|max:2000'
        ]);

        $answer = HelpAnswer::create([
            'help_request_id' => $helpRequest->id,
            'user_id' => auth()->id(),
            'answer_content' => $request->content,
            'is_hidden' => false
        ]);

        $answer->load('user');

        return response()->json([
            'answer' => $answer,
            'message' => 'Answer created successfully'
        ], 201);
    }

    /**
     * 标记为最佳答案
     */
    public function markAsBest(HelpAnswer $answer)
    {
        $helpRequest = $answer->helpRequest;

        // 只有提问者可以标记最佳答案
        if ($helpRequest->user_id !== auth()->id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // 取消其他答案的最佳标记
        HelpAnswer::where('help_request_id', $helpRequest->id)
            ->update(['is_best_answer' => false]);

        // 标记当前答案为最佳
        $answer->update(['is_best_answer' => true]);

        // 更新求助请求状态
        $helpRequest->update(['status' => 'resolved']);

        return response()->json([
            'message' => 'Answer marked as best'
        ]);
    }
}